import { asyncRoutes, constantRoutes } from '@/router'
import Layout from '@/layout'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  // 格式化菜单 // 从后端传过来的数据结构不一样
  /*
  "id": 864,
				"code": "system",
				"createAt": "2018-11-23T10:24:16",
				"createBy": 1,
				"description": "系统管理",
				"href": "/system",
				"icon": "xitong",
				"name": "系统管理",
				"order": 1,
				"parentId": 0,
				"path": "system",
				"status": 1,
				"type": "10",
				"updateAt": "2020-09-08T20:54:54+08:00",
				"updateBy": 2
  */
  /*
 {
    path: '/icon',
    component: Layout,
    children: [
      {
        path: 'index',
        component: () => import('@/views/icons/index'),
        name: 'Icons',
        meta: { title: 'Icons', icon: 'icon', noCache: true }
      }
    ]
  }
 */
  formatMenus({ commit }, menus) {
    return new Promise(resolve => {
      const routes = []
      menus.forEach(item => {
        if (item.parentId === 0) {
          // 该项已经存在，跳过
          if (routes.some(function(x) { return item.id === x.id })) {
            return false
          }
          routes.push({
            id: item.id,
            path: item.path,
            name: item.name,
            component: item.href === 'layout' ? Layout : resolve => require([`@/views/${item.href}`], resolve),
            meta: {
              title: item.name,
              icon: item.icon
            },
            children: []
          })
        }
        // 获取到父选项
        var parents = routes.filter(function(x, index) {
          return item.parentId === x.id
        })
        if (parents.length <= 0) {
          return false
        }

        var parentMenu = parents[0]
        parentMenu.children.push({
          id: item.id,
          path: item.path,
          name: item.name,
          component: resolve => require([`@/views/${item.href}`], resolve), // () => import(`@/views/${href}`),
          meta: { title: item.name, icon: item.icon }
        })
      })

      commit('SET_ROUTES', routes)
      resolve(routes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
